import React, {useState, useEffect, useMemo} from 'react';
import {Table} from 'antd';

import DetailCard from '~/page/FineBi/common/DetailCard';
import DetailModal from '~/page/FineBi/common/DetailModal';
import Loading from '~/page/FineBi/common/Loading';

import {parseDimensionAndValues, arrayColumnsTransform} from '~/page/FineBi/utils/convert';
import {
    queryValues,
    queryDetail,
    download,
    querySpringValues,
    querySpringExcelValues,
    querySpringPercentage
} from '~/service/refundReport';
import {CODE_7001} from '~/service/http';

const getValueFunc = {
    default: queryValues,
    renewRate: querySpringValues,
    renewPerson: querySpringExcelValues,
    percentRate: querySpringPercentage
};

const withPannel = Element => props => {
    // 数据格式有问题需要传过来unitId, 否则没法取，需要unitId来获取unitId obj
    const {
        dimensionAndValues = [], dId, unitId, isSearch = true, tableId,
        selectId, requestUrl = 'default'
    } = props;

    const [loading, setLoading] = useState(false);
    const [modalVisible, setModalVisible] = useState(false);
    const [title, setTitle] = useState();

    // 下钻
    const [drilingList, setDrilingList] = useState([]);

    // 详情数据
    const [detailData, setDetailData] = useState({});

    const [dataSource, setDataSource] = useState();

    const [tableData, setTableData] = useState({});
    const {columnList = [], value = []} = tableData || {};

    const pDimensionAndValues = useMemo(() => parseDimensionAndValues(dimensionAndValues, selectId), [
        dimensionAndValues,
        selectId
    ]);

    // 获取本块数据value
    const getData = (pDimensionAndValues, drilingList) => {
        const dashBoard = [
            {
                dashBoardName: dId,
                dashBoardId: dId
            }
        ];
        const param = {
            dimensionAndValues: pDimensionAndValues,
            dashBoardList: dashBoard,
            drilingList
        };
        setLoading(true);
        getValueFunc[requestUrl](param)
            .then(res => {
                const cardDetail = res?.data[dId] ?? null;
                if (cardDetail) {
                    const unitName = cardDetail[`${unitId}`]?.unitName || '';
                    const chart = cardDetail[`${unitId}`]?.chart || {};
                    const config = cardDetail[`${unitId}`]?.config || {};
                    const columnList = cardDetail[`${tableId}`]?.columnList || [];
                    const value = cardDetail[`${tableId}`]?.value || [];
                    if (tableId) {
                        const {newColumnList = [], newData = []} = arrayColumnsTransform(columnList, value);
                        setTableData({columnList: newColumnList, value: newData});
                    }
                    setTitle(unitName);
                    setDataSource({
                        chart,
                        config
                    });
                }
                else {
                    setDataSource();
                    setTableData({});
                }
            })
            .finally(code => {
                // 后端限流，啥也不操作
                if (code === CODE_7001) {
                    // return;
                }
                setLoading(false);
            });
    };

    const handleDownload = () => {
        const params = {
            unitId,
            drilingList,
            dimensionAndValues: pDimensionAndValues
        };
        const excelName = title ? title : null;
        download(params, excelName);
    };

    const handleDetail = () => {
        setModalVisible(true);
        const params = {
            unitId,
            drilingList,
            dimensionAndValues: pDimensionAndValues
        };
        queryDetail(params).then(res => {
            const {data} = res;
            setDetailData(data);
        });
    };

    // 下钻
    const handleDrilling = params => {
        const {info} = params;
        const {config = {}} = dataSource;
        const {dimensionList = []} = config;
        const [firstDimension] = dimensionList;
        const {dimensionId = '', dimensionName = ''} = firstDimension || {};
        const driling = {
            unitId,
            unitName: title,
            value: info?.name,
            dimensionId,
            dimensionName
        };
        setDrilingList([driling]);
    };

    const handleBack = () => {
        setDrilingList([]);
    };

    useEffect(() => {
        if (pDimensionAndValues && drilingList && isSearch) {
            getData(pDimensionAndValues, drilingList);
        }
    }, [pDimensionAndValues, drilingList, isSearch]);

    return (
        <div>
            <DetailCard
                style={{height: '100%'}}
                title={title || ' '}
                onDownload={handleDownload}
                onDetail={handleDetail}
                onBack={handleBack}
                showBack={drilingList?.length !== 0}
                showBtn={false}
            >
                <Loading loading={loading}>
                    <div className="stack-echarts-table-container">
                        <div className="stack-echarts-table">
                            {
                                tableId && value.length ? (
                                    <Table
                                        dataSource={value}
                                        columns={columnList}
                                        pagination={false}
                                        size="small"
                                        bordered
                                        scroll={{x: 300}}
                                    />
                                ) : null
                            }
                        </div>
                        <div className="stack-echarts">
                            <Element
                                {...props}
                                dataSource={dataSource}
                                onDrilling={handleDrilling}
                            />
                        </div>
                    </div>
                </Loading>
            </DetailCard>
            <DetailModal data={detailData} detailModalVisible={modalVisible} onCancel={() => setModalVisible(false)} />
        </div>
    );
};

export default withPannel;
